
void loop () 
{
    ////////////////////// START : Application code//////////////////////////////////
    RTC.convertTemperature();          //convert current temperature into registers
    float temp = RTC.getTemperature(); //Read temperature sensor value
    DateTime now = RTC.now();          //get the current date-time    
    
    processSwitchStatus(); 

#ifdef DEBUG
    displayBatteryStatus();
    displayDateAndTemp(now, temp);
#endif

    int percentage = battery.getPercentage();   
    writeToSdCard(now, temp, percentage, switchStatus);
    ////////////////////////END : Application code //////////////////////////////// 
    
    enableInterrupt();    
    powerDown();
    // ---- permanecemos aquí parados indefinidamente hasta que salte la interrupción --------
    awake();    
    //NO HACE FALTA DELAY AL FINAL DEL BUCLE
    
    
    DEBUG_PRINT (F("Free RAM: "));
    DEBUG_PRINT(String(Helper::availableMemory()) + "\n"); 

} 


int processSwitchStatus()
{
    bool stableInput = true;
    int switchReading = digitalRead(FLOAT_SWITCH_D_PIN);

     if (switchReading == SWITCH_OPEN)
       DEBUG_PRINT(F("Lectura Switch: En seco...\n"));
     else
       DEBUG_PRINT(F("Lectura Switch: Flotando...\n"));
     if (switchStatus == SWITCH_OPEN)
       DEBUG_PRINT(F("Estado Switch: En seco...\n"));
     else
       DEBUG_PRINT(F("Estado Switch: Flotando...\n"));

    long debounce = DEBOUNCE_TIME;   // the debounce time, increase if the output flickers
    if (switchReading != switchStatus)
    {
      long start = millis();         // the last time the output pin was toggled
      DEBUG_PRINT("Start: " + String(start) + "\n");
      long elapsed = 0;
      unsigned long i = 0;
      while (stableInput && elapsed < debounce)
      {
        int switchReading2 = digitalRead(FLOAT_SWITCH_D_PIN);
        if (switchReading2 != switchReading)
          stableInput = false;
        i++;
        elapsed = millis() - start;
        //Por si se desborda el contador de tiempo (daría un tiempo transcurrido negativo)

        if (elapsed < 0 )
          elapsed = debounce; 
      }
    }
    
    if (stableInput)
    {
       switchStatus = switchReading;
       if (switchStatus == SWITCH_OPEN)
       {
           DEBUG_PRINT(F("Switch estable En seco...\n"));
           //Encendemos el led de aviso si el flotador queda en estado abierto, es decir no flota
           //digitalWrite(DRY_LED_D_PIN, HIGH);
           ledBlink(DRY_LED_D_PIN, 5, 3, 200);
           sleepTime = SLEEP_TIME_SHORT;
       }
       else
       {
           DEBUG_PRINT(F("Switch estable Flotando...\n"));
           digitalWrite(DRY_LED_D_PIN, LOW);
           sleepTime = SLEEP_TIME_LONG;
       }
    }
}




void displayBatteryStatus()
{
  battery.update();
  //battery.ledflashStatus(POWER_LED_PIN, LED_FLASHES_FOR_FULL);
  float voltage = battery.getVoltage();
  int percentage = battery.getPercentage();
  char* CS = battery.getChStatus();
  bool ch = battery.isCharging();
  
  if (strcmp(CS, "done") == 0)
    digitalWrite(POWER_LED_D_PIN, HIGH);
  else
    digitalWrite(POWER_LED_D_PIN, LOW);
  
  DEBUG_PRINT(F("battery: "));
  DEBUG_PRINT(String(voltage,4));
  DEBUG_PRINT(F("V  -> "));
  DEBUG_PRINT(percentage);
  DEBUG_PRINT(F("%     Charge Status: "));
  DEBUG_PRINT(CS);
  DEBUG_PRINT(F("\n"));
}


void displayDateAndTemp(DateTime now, float temp)
{
    DEBUG_PRINT(Helper::timeToStr(now));
    DEBUG_PRINT("   ");
    DEBUG_PRINT(temp);
    DEBUG_PRINT(F(" deg C\n"));
}

void writeToSdCard(DateTime now, float temp, int batteryPercentage, int switchStatus)
{
  String txt =  Helper::timeToStr(now) + ", T:" + String(temp) + ", Bat:" + String(batteryPercentage) + "%";
  if (switchStatus == SWITCH_OPEN)
    txt += ", flotando\n";
  else
    txt += ", en seco\n";  
  appendToFile(fileName, txt);
}


//Parpadeo con espera (bloquea ejecución)
void ledBlink(int ledPin, int times, int timeOn, int timeOff)
{
    for (int i = 0; i < times ; i++)
    {
      digitalWrite(ledPin, HIGH);
      delay(timeOn);
      digitalWrite(ledPin, LOW);
    delay (timeOff);
    }
}



